import { getCommonUsers } from '@/api/exam/content';
import { PapersItem, getPapers } from '@/api/exam/paper';
import { getQuestions } from '@/api/exam/question';
import { Questions } from '@/api/question';
import { UserInfo } from '@/api/system/user';
import { questionTypeSelectOption } from '@/contants/table';
import { Input, Select, Table, DatePicker, Button } from 'antd';
import FormItem from 'antd/es/form/FormItem';
import React, { useEffect, useMemo, useState } from 'react';
import moment from 'moment';

const { RangePicker } = DatePicker;

interface Props {
  setVisible: (visible: boolean) => void;
  setQuestions: (question: Questions[]) => void;
  form: any;
}

const paperCloumns = [
  {
    title: '试卷名称',
    width: '250px',
    dataIndex: 'paperName',
    key: 'paperName'
  }
];

const userCloumns = [
  {
    title: '用户名称',
    width: '250px',
    dataIndex: 'nickname',
    key: 'nickname'
  }
];

export default function AddForm({ form, setVisible, setQuestions }: Props) {
  const [selectedPaperID, setSelectedPaperID] = useState<number>();
  const [paperName, setPaperName] = useState<string>('');
  const [paperDataSource, setPaperDataSource] = useState<PapersItem[]>([]);
  const filterPaperDataSource = useMemo(
    () => paperDataSource.filter((it: PapersItem) => !paperName || it.paperName.includes(paperName)),
    [paperName, paperDataSource]
  );

  const handleSelectPaperChange = (selectedRowKey: React.Key[]) => {
    setSelectedPaperID(selectedRowKey[0] as number);
  };

  const [userIDs, setUserIDs] = useState<React.Key[]>([]);
  const [nickname, setNickname] = useState<string>('');
  const [userDataSource, setUserDataSource] = useState<UserInfo[]>([]);
  const filterUserDataSource = useMemo(
    () => userDataSource.filter((it: UserInfo) => !nickname || it.nickname.includes(nickname)),
    [nickname, userDataSource]
  );

  const handleSelectUserChange = (ids: React.Key[]) => {
    setUserIDs(ids);
  };

  useEffect(() => {
    getPapers({
      isOpen: '否'
    }).then((res) => {
      setPaperDataSource(res.data);
    });
    getCommonUsers().then((res) => {
      setUserDataSource(res.data);
    });
  }, []);

  useEffect(() => {
    // TODO: paperID
    if (form && selectedPaperID) {
      form.setFieldsValue({
        paperID: selectedPaperID
      });
    }
  }, [selectedPaperID]);

  useEffect(() => {
    // TODO: paperID
    if (form && userIDs.length > 0) {
      form.setFieldsValue({
        userIDs
      });
    }
  }, [userIDs]);

  const handleToDetail = () => {
    setVisible(true);
    const paper = paperDataSource.find((it) => it._id === selectedPaperID);
    const currentQuestions = paper ? (JSON.parse(paper.paperContent) as unknown as Questions[]) : [];
    setQuestions(currentQuestions);
  };

  return (
    <>
      <FormItem labelCol={{ span: 4 }} label="考试名称" name="examName" rules={[{ required: true }]}>
        <Input placeholder="请输入考试名称" />
      </FormItem>
      <FormItem labelCol={{ span: 4 }} label="生效时间" name="time" rules={[{ required: true }]}>
        <RangePicker disabledDate={(current) => current && current < moment().endOf('hour')} showTime />
      </FormItem>
      <FormItem label="请选择试题" name="paperID" rules={[{ required: true }]}>
        <Select mode="tags" style={{ display: 'none' }} />
      </FormItem>
      <Table
        rowKey="_id"
        scroll={{ y: '250px' }}
        title={() => (
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <div>
              <Input.Search
                style={{ width: '250px' }}
                placeholder="请输入试卷名称模糊搜索"
                allowClear
                onSearch={(text) => setPaperName(text)}
              />
            </div>
            <div>
              <Button onClick={handleToDetail} disabled={!selectedPaperID}>
                查看试卷
              </Button>
            </div>
          </div>
        )}
        dataSource={filterPaperDataSource}
        columns={paperCloumns}
        rowSelection={{ type: 'radio', onChange: handleSelectPaperChange }}
      />
      <FormItem label="请选择考生" name="userIDs" rules={[{ required: true }]}>
        <Select mode="tags" style={{ display: 'none' }} />
      </FormItem>
      <Table
        rowKey="_id"
        scroll={{ y: '250px' }}
        title={() => (
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <div>
              <Input.Search
                style={{ width: '250px' }}
                placeholder="请输入考生姓名模糊搜索"
                allowClear
                onSearch={(text) => setNickname(text)}
              />
            </div>
          </div>
        )}
        dataSource={filterUserDataSource}
        columns={userCloumns}
        rowSelection={{
          selectedRowKeys: userIDs,
          onChange: handleSelectUserChange
        }}
      />
    </>
  );
}
